package org.unidata.mdm.rest.v1.meta.service.entities;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;

import org.unidata.mdm.meta.context.GetDataModelContext;
import org.unidata.mdm.meta.dto.GetModelDTO;
import org.unidata.mdm.rest.v1.meta.service.AbstractMetaModelRestService;

/**
 * Common entities rest service
 *
 * @author Alexandr Serov
 * @since 24.11.2020
 **/
public abstract class AbstractMetaEntitiesRestService extends AbstractMetaModelRestService {

    protected <T> T findFirstEntityByRequest(GetDataModelContext context, Function<GetModelDTO, List<T>> mapper) {
        List<T> entities = findEntitiesByRequest(context, mapper);
        T result = null;
        if (!entities.isEmpty()) {
            result = entities.get(0);
        }
        return result;
    }

    protected <T> List<T> findEntitiesByRequest(GetDataModelContext context, Function<GetModelDTO, List<T>> mapper) {
        GetModelDTO result = metaModelService.get(context);
        List<T> entities = mapper.apply(result);
        if (entities == null) {
            entities = Collections.emptyList();
        }
        return entities;
    }

}
